{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f0533b59",
   "metadata": {},
   "source": [
    "# （一）元组（tuple）\n",
    "\n",
    "* [元组](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)\n",
    "       \n",
    "> 1.它是和list几乎完全一样的序列数据  \n",
    "> 2.它与list不同的地方是：**不可变**（因为不可变，所以几乎没有办法）  \n",
    "> 3.元组的形式：（1,2,3,4,5）  对比  元组()   列表[]  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "cfbcfc9b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('10001', '10002', '10003', '10003')\n"
     ]
    }
   ],
   "source": [
    "stu_id = '10001','10002','10003','10003'\n",
    "print(stu_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "0eb1ffc9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tuple"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 对象类型\n",
    "type(stu_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "12253368",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查询数量\n",
    "stu_id.count('10003')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "99a90ef1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查询索引值\n",
    "stu_id.index('10002')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6d51b3f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 时间也不可变\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "f290e2b0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "time.struct_time(tm_year=2021, tm_mon=10, tm_mday=30, tm_hour=8, tm_min=54, tm_sec=15, tm_wday=5, tm_yday=303, tm_isdst=0)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "time.localtime()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b9b51a38",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((123, 456, 789), (1, 2, 3, 4, 5))"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 元组可以被嵌套\n",
    "t = (123,456,789)\n",
    "u = t, (1, 2, 3, 4, 5)\n",
    "u"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9a5c492",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16ea30c3",
   "metadata": {},
   "source": [
    "# （二）字典(dict )\n",
    "\n",
    "> 1. 存在意义的索引值——命名  \n",
    "> 2. keys:字符串（ages）+ 数值、元组来定义（唯一的，不可变的,不能用list来作为字典的索引值    \n",
    "> 3. 格式：  变量 = {'keys':values,'keys':values}   \n",
    "> 4. 字典是用来保存一个键的集合，其中每一个唯一的键有一个与之关联的值。（映射：x----y）  \n",
    "> 5. 字典是**无序的**，其不能维持对象插入时的顺序——使用键来查找值\n",
    "> 6. 可以把字典想成是一个行集，每一行只包含两列，第一列储存一个键，第二列储存一个值\n",
    "> 7. 各行成为一个值对，与列表相似，字典可以根据需要拓展和收缩\n",
    "> 8. 不允许同一个键出现两次。创建时如果同一个键被赋值两次，后一个值会被记住"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "85859488",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': 'ford prefect',\n",
       " 'Gender ': 'Male',\n",
       " 'Occupation': 'Research',\n",
       " 'Home planet': 'seven'}"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 举例：符合字典模型的数据——储存数据\n",
    "# 数据有两列，可能有多个数据行\n",
    "\n",
    "person01 = {\n",
    "             'Name': 'ford prefect',       # 字符串用引号包围\n",
    "             'Gender ': 'Male',\n",
    "             'Occupation' : 'Research',\n",
    "             'Home planet': 'seven'\n",
    "           }\n",
    "person01"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43116396",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85cf4900",
   "metadata": {},
   "source": [
    "### 中括号记法——访问字典\n",
    "> 1.列表用数值索引值访问数据    \n",
    "> 2.字典使用键来访问关联的数据值  \n",
    "> 3.访问字典里的值——把相应的键放入到方括号中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "744f88da",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'ford prefect'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "person01['Name']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "bee78fb3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict[name]: runoob\n"
     ]
    }
   ],
   "source": [
    "dict = {'name':'runoob','age':'23'}\n",
    "print('dict[name]:',dict['name'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95c8623a",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d27507d",
   "metadata": {},
   "source": [
    "### 如何创建字典？\n",
    "\n",
    "> 1.创建字典的三种常见的方法\n",
    ">> 1.直接按照字典的格式创建 ： {'keys1':'values1','keys2':'values2'}  \n",
    ">> 2.dict()函数来创建字典： dict(key1=values1,key2=values2)  \n",
    ">> 3.字典数据增加的方式：新建空字典 dict_name = []  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2dc6dd87",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu_10001': 'alex', 'stu_10002': 'jack'}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1.直接按照字典的格式创建（使用中括号）\n",
    "stu_info = {                          # 字典名 = 字符串 + 数值 （通常）\n",
    "            \"stu_10001\":\"alex\",\n",
    "            \"stu_10002\":\"jack\"\n",
    "}\n",
    "stu_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "42cee88f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu_10001': 'alex', 'stu_10002': 'jack'}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2.dict()函数来创建字典\n",
    "stu_info2 = dict(\n",
    "    stu_10001 = \"alex\",         # 与第一种区别：dict()/{}，stu_10001/'stu_10001'，=/:\n",
    "    stu_10002 = \"jack\"          # 逐行输入，使代码更易读\n",
    ")\n",
    "stu_info2 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "8772c379",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu_10001': 'Alex', 'stu_10002': 'John'}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3.新建空字典，然后增加值的方式创建字典\n",
    "stu_info3 = {}\n",
    "stu_info3['stu_10001'] = 'Alex'    \n",
    "stu_info3['stu_10002'] = 'John'    # 为一个新键（放在中括号里）赋一个对象来为字典增加新的值对。\n",
    "stu_info3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "2624a3f4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 0, 'e': 1, 'u': 0, 'i': 0, 'o': 0}"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## 回顾上一章——如何使用字典完成频度统计\n",
    "\n",
    "found = {}         # 新建字典\n",
    "# 为每个元音创建一行，并将其关联的值初始化为0\n",
    "found['a'] = 0\n",
    "found['e'] = 0\n",
    "found['u'] = 0\n",
    "found['i'] = 0\n",
    "found['o'] = 0\n",
    "\n",
    "# 根据需要更新频度——递增e的频度计数\n",
    "found['e'] += 1   # 自加1                       # found['e'] = found['e'] + 1\n",
    "found"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f5dc83a",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfb9180e",
   "metadata": {},
   "source": [
    "### 迭代处理字典\n",
    "> 1.用for循环迭代处理一个字典时，解释器只处理字典的键。  \n",
    "> 2.要访问关联的数据值，需要把各个键放在中括号里，结合使用字典名和键来访问这个键关联的值  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "72ba13d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a was found 0 time(s).\n",
      "e was found 1 time(s).\n",
      "u was found 0 time(s).\n",
      "i was found 0 time(s).\n",
      "o was found 0 time(s).\n"
     ]
    }
   ],
   "source": [
    "for i in found:\n",
    "    print(i,'was found', found[i],'time(s).')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cfdd250",
   "metadata": {},
   "source": [
    "* sorted 内置函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "cc777fae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n",
      "e\n",
      "i\n",
      "o\n",
      "u\n"
     ]
    }
   ],
   "source": [
    "# 指定输出时的字典顺序\n",
    "for i in sorted(found):                  # 按字母顺序输出\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe747000",
   "metadata": {},
   "source": [
    "* item函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "2e3e263d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a was found 0 times.\n",
      "e was found 1 times.\n",
      "i was found 0 times.\n",
      "o was found 0 times.\n",
      "u was found 0 times.\n"
     ]
    }
   ],
   "source": [
    "# 用item迭代处理字典\n",
    "for k,v in sorted(found.items()):             # for i in found.item()\n",
    "    print(k,'was found',v,'times.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b02251f",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b50290b",
   "metadata": {},
   "source": [
    "### 实际案例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "3aaa6df3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "provide a word to search for vowels:qiuxingqian\n",
      "a was found 1 times\n",
      "e was found 0 times\n",
      "i was found 3 times\n",
      "o was found 0 times\n",
      "u was found 1 times\n"
     ]
    }
   ],
   "source": [
    "### 给定一个单词时，它会为找到的各个元音生成一个频度计数  \n",
    "vowels = ['a','e','i','o','u']\n",
    "word = input('provide a word to search for vowels:')\n",
    "found = {}\n",
    "found['a'] = 0\n",
    "found['e'] = 0           # 字典的键必须初始化（少量数据可以此方法 = 0）\n",
    "found['i'] = 0           # 删除初始化代码会导致一个运行时错误——keyError——in操作符来避免\n",
    "found['o'] = 0\n",
    "found['u'] = 0\n",
    "for letter in word:\n",
    "    if letter in vowels:\n",
    "        found[letter] += 1              # 将found[letter]指示的词增1\n",
    "for k,v in sorted(found.items()):\n",
    "    print(k,'was found',v,'times')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e06ed078",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95636496",
   "metadata": {},
   "source": [
    "### 只显示找到的元音\n",
    "> 1.sorted内置函数：可以在输出中对字典排序  \n",
    "> 2.items方法：按值对迭代处理（否则，for只能解释键）  \n",
    "> 3.如果试图访问一个字典中不存在的键，会导致KeyError.  \n",
    "> 4.访问一个键前，要避免KeyError。in和not in操作符都可以提供帮助，但setdefault更成熟  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "faf18794",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'apples': 10, 'bananas': 1}"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用in来检查成员关系\n",
    "# 使用前确保初始化——动态创建值对（初始化大量数据时）\n",
    "\n",
    "fruits = {}\n",
    "fruits['apples'] = 10             # 直接赋值\n",
    "\n",
    "if 'bananas' in fruits:           # 查看'bananas'键是否在字典中\n",
    "    fruits['bananas'] += 1        # 在的话值就自加1\n",
    "else:\n",
    "    fruits['bananas'] = 1         # 如果不在，将它的值初始化为1\n",
    "fruits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "d27a8257",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'apples': 10, 'bananas': 1, 'pears': 12}"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用 not in 代替 in\n",
    "if 'pears' not in fruits:\n",
    "    fruits['pears'] = 0           # 初始化\n",
    "\n",
    "fruits['pears'] += 1              # 递增\n",
    "fruits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "835d6d28",
   "metadata": {},
   "outputs": [],
   "source": [
    "# setdefaults 方法——可以把一个不存在的键初始化为一个指定值\n",
    "fruits.setdefault('pears',0)      # 初始化\n",
    "fruits['pears'] += 1              # 递增\n",
    "fruits"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f63e17c",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b59ab33b",
   "metadata": {},
   "source": [
    "### 实际案例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "99a59681",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "provide a word to search for vowels:qiuxingqian\n",
      "a was found 1 times\n",
      "i was found 3 times\n",
      "u was found 1 times\n"
     ]
    }
   ],
   "source": [
    "# 使用setdefault方法\n",
    "vowels = ['a','e','i','o','u']\n",
    "word = input('provide a word to search for vowels:')\n",
    "found = {}\n",
    "for letter in word:\n",
    "    if letter in vowels:\n",
    "        found.setdefault(letter,0)      # 避免了KeyError问题，同时有不用花时间提前初始化字典中的所有数据行\n",
    "        found[letter] += 1              # 将found[letter]指示的词增1\n",
    "for k,v in sorted(found.items()):\n",
    "    print(k,'was found',v,'times')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3fbe5a6b",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bcb1271b",
   "metadata": {},
   "source": [
    "### 复制的数据结构"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e07f10cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 嵌套字典\n",
    "Name         Gender        Occupation         Home Planet\n",
    "ford          Male          Researcher          seven\n",
    "dent          Male          maker               earth\n",
    "McMillan      Female        Mathematician       earth\n",
    "Marvin        Unknown       Android             unknown"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "2426a87e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ford': {'Name': 'ford prefect',\n",
       "  'Gender ': 'Male',\n",
       "  'Occupation': 'Research',\n",
       "  'Home planet': 'seven'},\n",
       " 'dent': {'Name': 'dent',\n",
       "  'Gender ': 'Male',\n",
       "  'Occupation': 'maker',\n",
       "  'Home planet': 'earth'},\n",
       " 'McMillan': {'Name': 'McMillan',\n",
       "  'Gender ': 'F',\n",
       "  'Occupation': 'Research',\n",
       "  'Home planet': 'seven'},\n",
       " 'Marvin': {'Name': 'Marvin',\n",
       "  'Gender ': 'Unknown',\n",
       "  'Occupation': 'Android',\n",
       "  'Home planet': 'unknown'}}"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 只创建1个字典来储存数据\n",
    "people = {}                 # 新建一个空字典\n",
    "people['ford'] = {                        # 键是'ford'  值是另一个字典\n",
    "             'Name': 'ford prefect',       \n",
    "             'Gender ': 'Male',\n",
    "             'Occupation' : 'Research',\n",
    "             'Home planet': 'seven'\n",
    "}\n",
    "people['dent'] = {\n",
    "             'Name': 'dent',       \n",
    "             'Gender ': 'Male',\n",
    "             'Occupation' : 'maker',\n",
    "             'Home planet': 'earth'\n",
    "}\n",
    "people['McMillan'] = {\n",
    "             'Name': 'McMillan',       \n",
    "             'Gender ': 'F',\n",
    "             'Occupation' : 'Research',\n",
    "             'Home planet': 'seven'\n",
    "}\n",
    "people['Marvin'] = {\n",
    "             'Name': 'Marvin',       \n",
    "             'Gender ': 'Unknown',\n",
    "             'Occupation' : 'Android',\n",
    "             'Home planet': 'unknown'\n",
    "}\n",
    "people"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "17c3709c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Marvin': {'Gender ': 'Unknown',\n",
      "            'Home planet': 'unknown',\n",
      "            'Name': 'Marvin',\n",
      "            'Occupation': 'Android'},\n",
      " 'McMillan': {'Gender ': 'F',\n",
      "              'Home planet': 'seven',\n",
      "              'Name': 'McMillan',\n",
      "              'Occupation': 'Research'},\n",
      " 'dent': {'Gender ': 'Male',\n",
      "          'Home planet': 'earth',\n",
      "          'Name': 'dent',\n",
      "          'Occupation': 'maker'},\n",
      " 'ford': {'Gender ': 'Male',\n",
      "          'Home planet': 'seven',\n",
      "          'Name': 'ford prefect',\n",
      "          'Occupation': 'Research'}}\n"
     ]
    }
   ],
   "source": [
    "### 美化打印的复杂数据结构\n",
    "import pprint\n",
    "pprint.pprint(people)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "abee0188",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'maker'"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 访问一个复杂数据结构的数据\n",
    "# ——dent是做什么工作的？\n",
    "people['dent']['Occupation']     # 通过中括号可以指定你感兴趣的行和列，从表中访问任何数据值\n",
    "  #      行       列"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "821306a6",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26ebba90",
   "metadata": {},
   "source": [
    "# （三）字典方法的练习"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b40bac23",
   "metadata": {},
   "source": [
    "### 增加字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "id": "af53187e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': 'Runoob', 'Age': 7, 'class': 'Frist'}"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict = {'Name': 'Runoob', 'Age': 7}\n",
    "dict['class'] = 'Frist'\n",
    "dict"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81176db2",
   "metadata": {},
   "source": [
    "### 修改字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "id": "6f0737b7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict['Age']:  8\n",
      "dict['School']:  NFCA\n"
     ]
    }
   ],
   "source": [
    "# 向字典添加新内容的方法是增加新的键/值对，修改或删除已有键/值对\n",
    "dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}\n",
    " \n",
    "dict['Age'] = 8                 # 更新 Age\n",
    "dict['School'] = \"NFCA\"         # 添加信息\n",
    " \n",
    "print (\"dict['Age']: \", dict['Age'])\n",
    "print (\"dict['School']: \", dict['School'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2efe2e90",
   "metadata": {},
   "source": [
    "### clear()——删除字典内所有元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "6cc94b7e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 清空列表\n",
    "dict.clear()\n",
    "dict"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19cfbfe0",
   "metadata": {},
   "source": [
    "### len()——计算字典元素个数，即键的总数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "28d2171a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}\n",
    "len(dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e093388a",
   "metadata": {},
   "source": [
    "### str()——输出字典，可以打印的字符串表示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "be4c9378",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"{'Name': 'Runoob', 'Age': 7, 'Class': 'First'}\""
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70b8bc27",
   "metadata": {},
   "source": [
    "### type()——返回输入的变量类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "4b9a4768",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b8d29e7",
   "metadata": {},
   "source": [
    "### copy()——返回一个字典的浅复制。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "4ee5b934",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "新复制的字典为 :  {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}\n"
     ]
    }
   ],
   "source": [
    "dict1 = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} \n",
    "dict2 = dict1.copy()  \n",
    "\n",
    "print (\"新复制的字典为 : \",dict2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e10814de",
   "metadata": {},
   "source": [
    "### fromkeys()——创建一个新字典，以序列seq中元素做字典的键，val为字典所有键对应的初始值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "d9488683",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "新的字典为 : {'name': None, 'age': None, 'sex': None}\n",
      "新的字典为 : {'name': 10, 'age': 10, 'sex': 10}\n"
     ]
    }
   ],
   "source": [
    "# fromkeys() 方法语法：dict.fromkeys(seq[, value])    value: 默认为 None。\n",
    "seq = ('name', 'age', 'sex')\n",
    " \n",
    "dict = dict.fromkeys(seq)\n",
    "print (\"新的字典为 : %s\" %  str(dict))\n",
    " \n",
    "dict = dict.fromkeys(seq, 10)\n",
    "print (\"新的字典为 : %s\" %  str(dict))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c98653b4",
   "metadata": {},
   "source": [
    "### get()——函数返回指定键的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "id": "1e1afab3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "27"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# get()方法语法：dict.get(key, default=None)\n",
    "# default -- 如果指定的键不存在时，返回该默认值。\n",
    "dict = {'Name': 'Runoob', 'Age': 27}\n",
    "dict.get('Age')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9421751d",
   "metadata": {},
   "source": [
    "### in 操作符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "45570c33",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "键 Age 存在\n",
      "键 Age 存在\n"
     ]
    }
   ],
   "source": [
    "# in 操作符用于判断键是否存在于字典中，如果键在字典 dict 里返回 true，否则返回 false\n",
    "# 而 not in 操作符刚好相反，如果键在字典 dict 里返回 false，否则返回 true\n",
    "\n",
    "# in\n",
    "# 检测键 Age 是否存在\n",
    "if  'Age' in dict:\n",
    "    print(\"键 Age 存在\")\n",
    "else :\n",
    "    print(\"键 Age 不存在\")\n",
    "    \n",
    "# not in\n",
    "# 检测键 Age 是否存在\n",
    "if  'Age' not in dict:\n",
    "    print(\"键 Age 不存在\")\n",
    "else :\n",
    "    print(\"键 Age 存在\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7466795",
   "metadata": {},
   "source": [
    "### items()——以列表返回视图对象，是一个可遍历的键对"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "id": "5167d12e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_items([('Name', 'Runoob'), ('Age', 27)])"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 方法语法：dict.items()\n",
    "dict.items()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa2f5225",
   "metadata": {},
   "source": [
    "### keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "id": "caf4df68",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['Name', 'Age'])"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict.keys()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e18a33e",
   "metadata": {},
   "source": [
    "### setdefault() 与 get()方法相似"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "45b1357f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 方法语法：dict.setdefault(key, default=None)\n",
    "dict = {'Name': 'Runoob', 'Age': 7}\n",
    "dict.setdefault('Age',None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66b1cdc5",
   "metadata": {},
   "source": [
    "### update() —— 把字典参数 dict2 的 key/value(键/值) 对更新到字典 dict 里"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "id": "c9f3e97a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "更新字典 dict :  {'Name': 'Runoob', 'Age': 7, 'Sex': 'female'}\n"
     ]
    }
   ],
   "source": [
    "# 方法语法：dict.update(dict2)\n",
    "dict = {'Name': 'Runoob', 'Age': 7}\n",
    "dict2 = {'Sex': 'female' }\n",
    " \n",
    "dict.update(dict2)\n",
    "print (\"更新字典 dict : \", dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e96e2884",
   "metadata": {},
   "source": [
    "### popitem() ——随机返回并删除字典中的最后一对键和值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "id": "8e0582c2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('url', 'www.runoob.com')\n",
      "{'name': 'qiu', 'alexa': 10000}\n"
     ]
    }
   ],
   "source": [
    "site = {'name': 'qiu', 'alexa': 10000, 'url': 'www.runoob.com'}\n",
    "pop_obj = site.popitem()\n",
    "print(pop_obj)   \n",
    "print(site)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84ff957a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
